//
//  HBMyProblemsCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/12/9.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBMyProblemsCtrl.h"
#import "HBMyProblemDetailCtrl.h"
#import "HBMyProblemCell.h"

#import "HBGetProblemListInfo.h"
#import "HBGetProblemListItemInfo.h"
#import "HBGetProblemListParam.h"
#import "HBGetProblemListParser.h"

#import "MJRefresh.h"


@interface HBMyProblemsCtrl ()
<UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) HBGetProblemListInfo *problemListInfo;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic) int pageNum;

@end

@implementation HBMyProblemsCtrl

#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"常见问题";
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:_tableView];
    INIT_TABLE(_tableView);
    
    __weak UITableView *tableView = self.tableView;
    __weak typeof(self) weakSelf = self;
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
//        [weakSelf hideEmptyIV];
        weakSelf.pageNum = 1;
        [weakSelf requestToGetProblemList];
        
        if (tableView.mj_footer)
        {
            [tableView.mj_footer resetNoMoreData];
        }
        
        //        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            // 结束刷新
        //            [tableView.mj_header endRefreshing];
        //        });
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        //        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            // 结束刷新
        //            [tableView.mj_footer endRefreshing];
        //        });
        
        if (weakSelf.problemListInfo.dataAry.count>0)
        {
            weakSelf.pageNum++;
            [weakSelf requestToGetProblemList];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 结束刷新
                [tableView.mj_footer endRefreshing];
            });
        }
        
    }];
    
//    [self.tableView.mj_header beginRefreshing];
    
    self.pageNum = 1;
    [self requestToGetProblemList];
    
    
}

#pragma mark - private

- (void)uploadMyMsgListCell:(HBMyProblemCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
     HBGetProblemListItemInfo *itemInfo = self.problemListInfo.dataAry[indexPath.row];
    [cell setSubTitle:itemInfo.problemTitle];
}

- (CGFloat)getMsgCellHeightWithSubTitle:(NSString *)subTitle
{
    //@"好玩好赚-送体验金官方，赢了随时换钱，刺激火爆-送体验金下载，好赢就是硬道理！送体验金官方，24小时客服兑分服务，网络顶级送体验金平台"
    
    UILabel *subTitleLable = [self createLableWithTextColor:[LCCommon getColor:@"999999"] font:[UIFont systemFontOfSize:16.0f] text:subTitle textAlignment:NSTextAlignmentLeft frame:CGRectMake(900, 15, SCREEN_WIDTH-40, 10.0f) superView:self.view numberOfLines:0];
    
    CGRect lableFrame = subTitleLable.frame;
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:subTitle];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:8];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, subTitle.length)];
    subTitleLable.attributedText = attributedString;
    [subTitleLable sizeToFit];
    
    CGRect lableFrameNew = subTitleLable.frame;
    lableFrameNew.origin = lableFrame.origin;
    subTitleLable.frame = lableFrameNew;
    
    CGFloat height = subTitleLable.y + subTitleLable.height + 13;
    
    [subTitleLable removeFromSuperview];
    
    return height;
    
}

- (UILabel *)createLableWithTextColor:(UIColor *)color font:(UIFont *)font text:(NSString *)text textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView numberOfLines:(NSInteger)numberOfLines
{
    UILabel *lable = [[UILabel alloc]initWithFrame:frame];
    lable.textColor = color;
    lable.font = font;
    lable.text = text;
    lable.textAlignment = textAlignment;
    lable.numberOfLines = numberOfLines;
    [superView addSubview:lable];
    return lable;
}


#pragma mark - active



#pragma mark - delegate&datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.problemListInfo.dataAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = NSStringFromClass([HBMyProblemCell class]);;
    
    HBMyProblemCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell)
    {
        cell = [[HBMyProblemCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    [self uploadMyMsgListCell:(HBMyProblemCell *)cell atIndexPath:indexPath];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1/[UIScreen mainScreen].scale;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/[UIScreen mainScreen].scale)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HBGetProblemListItemInfo *itemInfo = self.problemListInfo.dataAry[indexPath.row];
    
    return [self getMsgCellHeightWithSubTitle:itemInfo.problemTitle];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     HBGetProblemListItemInfo *itemInfo = self.problemListInfo.dataAry[indexPath.row];
    HBMyProblemDetailCtrl *detailCtrl = [[HBMyProblemDetailCtrl alloc]init];
    detailCtrl.webUrl = itemInfo.problemUrl;
    [self.navigationController pushViewController:detailCtrl animated:YES];
    
}

#pragma mark - net

- (void)requestToGetProblemList
{
        [CustomLoadingView showHudToView:self.view];
        HBGetProblemListParam *param = [[HBGetProblemListParam alloc]init];
        param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
        param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
        param.pageNum = [NSString stringWithFormat:@"%d",self.pageNum];
        HBGetProblemListParser *parser = [[HBGetProblemListParser alloc]init];
    
    [NetCenter getDataFromURL:Method_getProblemList params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (self.pageNum==1)
        {
            [self.tableView.mj_header endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (myResult.code==0)
        {
            HBGetProblemListInfo *listInfo = (HBGetProblemListInfo *)myResult.result;
            if (self.pageNum==1)
            {
                self.problemListInfo = listInfo;
                [self.tableView reloadData];
                if (self.problemListInfo.dataAry.count==0)
                {
                   
                }
            }
            else
            {
                if (listInfo.dataAry.count>0)
                {
                    NSMutableArray *array = [NSMutableArray arrayWithArray:self.problemListInfo.dataAry];
                    [array addObjectsFromArray:listInfo.dataAry];
                    self.problemListInfo.dataAry = array;
                    [self.tableView reloadData];
                }
                else
                {
                    self.pageNum--;
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            //                self.msgListInfo = listInfo;
            //                [self.tableView reloadData];
        }
        else
        {
            DISSMISS_ERR(myResult.message);
            if (self.pageNum>1)
            {
                self.pageNum--;
            }
        }
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
        if (self.pageNum==1)
        {
            [self.tableView.mj_header endRefreshing];
        }
        else
        {
            [self.tableView.mj_footer endRefreshing];
            self.pageNum--;
        }
        
    }];
}

@end
